觀前提醒:
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
確認該數字是否為質數
"isPrime()" 的 function。/**
* @param {number} n
* @return {number}
*/
var countPrimes = function (n) {
let countOfPrime = 0;
for (let i = 1; i < n; i++) {
if (isPrime(i)) countOfPrime++;
}
return countOfPrime;
function isPrime(a) {
if (a <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (let x = 2; x * x <= a; x++) {
if (a % x === 0) {
return false;
}
}
return true;
}
};
這個 Easy 題,確實也是需要花點腦筋來思考的,尤其是撰寫 isPrime(a) 這個 function 時,小弟也參考了維基百科中,質數裡面的測試質數與整數分解這個章節,裡面的試除法給了我不少靈感,便採取此一方式來撰寫我的演算法~
謝謝大家的收看,LeetCode 小學堂我們下次見~